<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI客服接口测试页面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            padding: 30px;
        }

        .test-panel {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 25px;
            border: 2px solid #e9ecef;
        }

        .test-panel h3 {
            color: #495057;
            margin-bottom: 20px;
            font-size: 1.3em;
            display: flex;
            align-items: center;
        }

        .test-panel h3::before {
            content: '🚀';
            margin-right: 10px;
            font-size: 1.2em;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #495057;
        }

        input, textarea, select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #dee2e6;
            border-radius: 10px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        input:focus, textarea:focus, select:focus {
            outline: none;
            border-color: #4facfe;
            box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
        }

        textarea {
            resize: vertical;
            min-height: 100px;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 10px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.3s ease;
            width: 100%;
            margin-bottom: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .btn-stream {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
        }

        .btn-async {
            background: linear-gradient(135deg, #26de81 0%, #20bf6b 100%);
        }

        .response-area {
            background: white;
            border: 2px solid #dee2e6;
            border-radius: 10px;
            padding: 20px;
            min-height: 200px;
            max-height: 400px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.6;
        }

        .loading {
            display: none;
            text-align: center;
            color: #6c757d;
            font-style: italic;
        }

        .loading.show {
            display: block;
        }

        .stream-content {
            background: #e3f2fd;
            border-left: 4px solid #2196f3;
            padding: 15px;
            margin: 10px 0;
            border-radius: 5px;
        }

        .error {
            background: #ffebee;
            border-left: 4px solid #f44336;
            color: #c62828;
            padding: 15px;
            margin: 10px 0;
            border-radius: 5px;
        }

        .success {
            background: #e8f5e8;
            border-left: 4px solid #4caf50;
            color: #2e7d32;
            padding: 15px;
            margin: 10px 0;
            border-radius: 5px;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .stat-item {
            background: white;
            padding: 15px;
            border-radius: 10px;
            text-align: center;
            border: 2px solid #e9ecef;
        }

        .stat-value {
            font-size: 1.5em;
            font-weight: bold;
            color: #495057;
        }

        .stat-label {
            font-size: 0.9em;
            color: #6c757d;
            margin-top: 5px;
        }

        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 AI客服接口测试</h1>
            <p>测试同步、异步和流式聊天接口的性能和功能</p>
        </div>

        <div class="main-content">
            <div class="test-panel">
                <h3>测试配置</h3>
                
                <div class="form-group">
                    <label for="message">消息内容:</label>
                    <textarea id="message" placeholder="请输入要发送的消息...">你好，我想了解一下商品信息</textarea>
                </div>

                <div class="form-group">
                    <label for="sessionId">会话ID:</label>
                    <input type="text" id="sessionId" placeholder="留空自动生成" value="test-session-001">
                </div>

                <div class="form-group">
                    <label for="serverUrl">服务器地址:</label>
                    <input type="text" id="serverUrl" placeholder="服务器地址" value="http://localhost:8080">
                </div>

                <div class="form-group">
                    <label for="apiType">接口类型:</label>
                    <select id="apiType">
                        <option value="sync">同步接口 (/api/chat/send)</option>
                        <option value="async">异步接口 (/api/chat/send-async)</option>
                        <option value="stream" selected>流式接口 (/api/chat/stream)</option>
                    </select>
                </div>

                <button class="btn" type="button" onclick="testChat(); return false;">🚀 发送测试</button>
                <button class="btn btn-async" type="button" onclick="testAsync(); return false;">⚡ 异步测试</button>
                <button class="btn btn-stream" type="button" onclick="testStream(); return false;">📡 流式测试</button>
                
                <div class="stats">
                    <div class="stat-item">
                        <div class="stat-value" id="responseTime">0</div>
                        <div class="stat-label">响应时间(ms)</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value" id="requestCount">0</div>
                        <div class="stat-label">请求次数</div>
                    </div>
                </div>
            </div>

            <div class="test-panel">
                <h3>响应结果</h3>
                <div class="loading" id="loading">⏳ 正在处理请求...</div>
                <div class="response-area" id="responseArea">
                    <div style="color: #6c757d; text-align: center; padding: 50px;">
                        📝 响应内容将在这里显示
                    </div>
                </div>
                <button class="btn" type="button" onclick="clearResponse(); return false;" style="margin-top: 15px;">🗑️ 清空结果</button>
            </div>
        </div>
    </div>

    <script>
        let requestCount = 0;
        let startTime = 0;

        function updateStats(responseTime) {
            requestCount++;
            document.getElementById('responseTime').textContent = responseTime;
            document.getElementById('requestCount').textContent = requestCount;
        }

        function showLoading() {
            document.getElementById('loading').classList.add('show');
        }

        function hideLoading() {
            document.getElementById('loading').classList.remove('show');
        }

        function appendResponse(content, type = 'info') {
            const responseArea = document.getElementById('responseArea');
            const div = document.createElement('div');
            div.className = type;
            div.innerHTML = content;
            responseArea.appendChild(div);
            responseArea.scrollTop = responseArea.scrollHeight;
        }

        function clearResponse() {
            document.getElementById('responseArea').innerHTML = '<div style="color: #6c757d; text-align: center; padding: 50px;">📝 响应内容将在这里显示</div>';
        }

        async function testChat() {
            const message = document.getElementById('message').value;
            const sessionId = document.getElementById('sessionId').value;
            const serverUrl = document.getElementById('serverUrl').value;
            
            if (!message.trim()) {
                appendResponse('❌ 请输入消息内容', 'error');
                return;
            }

            if (!serverUrl.trim()) {
                appendResponse('❌ 请输入服务器地址', 'error');
                return;
            }

            showLoading();
            startTime = Date.now();

            try {
                const response = await fetch(`${serverUrl}/api/chat/send`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        message: message,
                        sessionId: sessionId || undefined
                    })
                });

                const data = await response.json();
                const responseTime = Date.now() - startTime;
                
                hideLoading();
                updateStats(responseTime);

                if (data.code === 200) {
                    appendResponse(`
                        <strong>✅ 同步请求成功</strong><br>
                        <strong>响应时间:</strong> ${responseTime}ms<br>
                        <strong>会话ID:</strong> ${data.data.sessionId}<br>
                        <strong>回复内容:</strong> ${data.data.reply}
                    `, 'success');
                } else {
                    appendResponse(`❌ 请求失败: ${data.message}`, 'error');
                }
            } catch (error) {
                hideLoading();
                appendResponse(`❌ 网络错误: ${error.message}`, 'error');
            }
        }

        async function testAsync() {
            const message = document.getElementById('message').value;
            const sessionId = document.getElementById('sessionId').value;
            const serverUrl = document.getElementById('serverUrl').value;
            
            if (!message.trim()) {
                appendResponse('❌ 请输入消息内容', 'error');
                return;
            }

            if (!serverUrl.trim()) {
                appendResponse('❌ 请输入服务器地址', 'error');
                return;
            }

            showLoading();
            startTime = Date.now();

            try {
                const response = await fetch(`${serverUrl}/api/chat/send-async`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        message: message,
                        sessionId: sessionId || undefined
                    })
                });

                const data = await response.json();
                const responseTime = Date.now() - startTime;
                
                hideLoading();
                updateStats(responseTime);

                if (data.code === 200) {
                    appendResponse(`
                        <strong>⚡ 异步请求成功</strong><br>
                        <strong>响应时间:</strong> ${responseTime}ms<br>
                        <strong>会话ID:</strong> ${data.data.sessionId}<br>
                        <strong>回复内容:</strong> ${data.data.reply}
                    `, 'success');
                } else {
                    appendResponse(`❌ 请求失败: ${data.message}`, 'error');
                }
            } catch (error) {
                hideLoading();
                appendResponse(`❌ 网络错误: ${error.message}`, 'error');
            }
        }

        function testStream() {
            const message = document.getElementById('message').value;
            const sessionId = document.getElementById('sessionId').value;
            const serverUrl = document.getElementById('serverUrl').value;
            
            if (!message.trim()) {
                appendResponse('❌ 请输入消息内容', 'error');
                return;
            }

            if (!serverUrl.trim()) {
                appendResponse('❌ 请输入服务器地址', 'error');
                return;
            }

            showLoading();
            startTime = Date.now();

            // 创建流式内容容器
            const streamDiv = document.createElement('div');
            streamDiv.className = 'stream-content';
            const streamId = 'streamText_' + Date.now();
            streamDiv.innerHTML = '<strong>📡 流式响应:</strong><br><span id="' + streamId + '"></span>';
            document.getElementById('responseArea').appendChild(streamDiv);
            
            const streamTextElement = document.getElementById(streamId);

            // 使用fetch进行流式请求
            fetch(`${serverUrl}/api/chat/stream`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    message: message,
                    sessionId: sessionId || undefined
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                
                function readStream() {
                    return reader.read().then(({ done, value }) => {
                        if (done) {
                            const responseTime = Date.now() - startTime;
                            hideLoading();
                            updateStats(responseTime);
                            appendResponse(`✅ 流式请求完成，总耗时: ${responseTime}ms`, 'success');
                            return;
                        }
                        
                        const chunk = decoder.decode(value, { stream: true });
                        const lines = chunk.split('\n');
                        
                        lines.forEach(line => {
                            if (line.startsWith('data: ')) {
                                const data = line.substring(6);
                                if (data && data !== '[DONE]') {
                                    try {
                                        const parsed = JSON.parse(data);
                                        if (parsed.name === 'data') {
                                            streamTextElement.textContent += parsed.data;
                                        } else if (parsed.name === 'start') {
                                            hideLoading();
                                            streamTextElement.innerHTML = '<em style="color: #666;">' + parsed.data + '</em><br>';
                                        } else if (parsed.name === 'end') {
                                            const responseTime = Date.now() - startTime;
                                            updateStats(responseTime);
                                            appendResponse(`✅ 流式请求完成，总耗时: ${responseTime}ms`, 'success');
                                            return;
                                        } else if (parsed.name === 'error') {
                                            appendResponse(`❌ 流式请求错误: ${parsed.data}`, 'error');
                                            return;
                                        }
                                    } catch (e) {
                                        // 忽略解析错误
                                    }
                                }
                            }
                        });
                        
                        return readStream();
                    });
                }
                
                return readStream();
            })
            .catch(error => {
                hideLoading();
                appendResponse(`❌ 流式请求失败: ${error.message}`, 'error');
            });
        }

        // 防止页面刷新
        window.addEventListener('beforeunload', function(e) {
            if (requestCount > 0) {
                e.preventDefault();
                e.returnValue = '确定要离开吗？测试结果将会丢失。';
                return '确定要离开吗？测试结果将会丢失。';
            }
        });

        // 防止表单提交导致页面刷新
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) {
                e.preventDefault();
                // 根据当前选择的接口类型执行对应的测试
                const apiType = document.getElementById('apiType').value;
                if (apiType === 'sync') {
                    testChat();
                } else if (apiType === 'async') {
                    testAsync();
                } else if (apiType === 'stream') {
                    testStream();
                }
                return false;
            }
        });

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            appendResponse('🎉 AI客服测试页面已加载，请选择测试类型开始测试！', 'success');
            
            // 保存服务器地址到本地存储
            const serverUrlInput = document.getElementById('serverUrl');
            const savedUrl = localStorage.getItem('ai-chat-server-url');
            if (savedUrl) {
                serverUrlInput.value = savedUrl;
            }
            
            serverUrlInput.addEventListener('change', function() {
                localStorage.setItem('ai-chat-server-url', this.value);
            });
        });
    </script>
</body>
</html>